package com.liuqi.voicenotes.reminder

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.liuqi.voicenotes.R

class ReminderReceiver : BroadcastReceiver() {
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    override fun onReceive(context: Context, intent: Intent) {
        val title = intent.getStringExtra("title") ?: "待办提醒"
        val isPre = intent.getBooleanExtra("is_pre", false)
        val channelId = "voicenotes.reminders"
        val nTitle = if (isPre) "即将到期提醒" else "到期提醒"
        val lead = ReminderScheduler.getLeadMinutes(context)
        val nText = if (isPre) "${lead}分钟后：$title" else title
        val notification = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(nTitle)
            .setContentText(nText)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .build()
        try {
            NotificationManagerCompat.from(context).notify((title.hashCode() + if (isPre) 1 else 0), notification)
        } catch (_: SecurityException) {
            // 未授予通知权限时，跳过通知但仍然进行语音播报
        }

        // 语音播报改由前台服务执行，避免后台限制导致的权限错误
        val svc = Intent(context, ReminderSpeakService::class.java).apply {
            putExtra("title", title)
            putExtra("is_pre", isPre)
        }
        ContextCompat.startForegroundService(context, svc)
    }
}